package com.central.apps.handler.purchase;

import com.central.app.common.base.BaseHandler;
import com.central.app.service.HandlerService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.exception.service.ServiceException;
import com.central.common.web.PageResult;
import com.central.common.web.Result;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.crypto.tls.MACAlgorithm;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * 处理采购计划业务逻辑
 *
 * @author lidachao
 * @date 2022/7/28
 */
@Component
@Slf4j
public class PurchasePlanHandler extends BaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        if ("getItemType".equals(type)) {
            String purchasecategory = MapUtils.getString(params, "purchasecategory");

            if (StringUtils.isEmpty(purchasecategory)) {
                return null;
            }

            String dictCode = "pr_itemtype";
            switch (purchasecategory) {
                case "服务":
                    dictCode = "pr_server_type";
                    break;
                case "生产外协":
                    dictCode = "pr_product_type";
                    break;
                case "科研外协":
                    dictCode = "pr_research_type";
                    break;
                case "物资":
                default:
                    break;
            }
            // 查询数据字典信息
            List<Map<String, Object>> dictSql = handlerService.findBySql("select code, name from sys_dict where pid in (select id from sys_dict where code = '" + dictCode + "')");
            if (CollectionUtils.isNotEmpty(dictSql)) {
                return PageResult.<Map<String, Object>>builder().data(dictSql).code(0).count((long) dictSql.size()).build();
            }
        } else if ("getProjectType".equals(type)) {
            String itemtype = MapUtils.getString(params, "itemtype");

            if (StringUtils.isEmpty(itemtype)) {
                return null;
            }

            StringBuilder sb = new StringBuilder();
            sb.append("'其他项目'");
            if (!itemtype.contains("A1类")) {
                sb.append(",");
                sb.append("'政府采购项目'");
            }
            // 查询数据字典信息
            List<Map<String, Object>> dictSql = handlerService.findBySql("select code, name from sys_dict where " +
                    " pid in (select id from sys_dict where code = 'pp_projecttype')" +
                    " and code in (" + sb + ")");
            if (CollectionUtils.isNotEmpty(dictSql)) {
                return PageResult.<Map<String, Object>>builder().data(dictSql).code(0).count((long) dictSql.size()).build();
            }
        } else if ("getPurchaseWay".equals(type)) {
            String itemtype = MapUtils.getString(params, "itemtype");
            String projecttype = MapUtils.getString(params, "projecttype");
            if (StringUtils.isEmpty(itemtype) || StringUtils.isEmpty(projecttype)) {
                return null;
            }

            StringBuilder sb = new StringBuilder();
            switch (projecttype) {
                case "政府采购":
                    sb.append("'线下采购'");
                    break;
                case "非政府采购":
                    sb.append("'线下采购','电商采购'");
                    break;
            }
            List<Map<String, Object>> dictSql = handlerService.findBySql("select code, name from sys_dict where pid in (select id from sys_dict where code = 'po_purchaseway') and  code in (" + sb + ")");
            if (CollectionUtils.isNotEmpty(dictSql)) {
                return PageResult.<Map<String, Object>>builder().data(dictSql).code(0).count((long) dictSql.size()).build();
            }
        } else if ("getQuotaMethod".equals(type)) {
            String itemtype = MapUtils.getString(params, "itemtype");

            if (StringUtils.isEmpty(itemtype)) {
                return null;
            }
            // 查询数据字典信息
            List<Map<String, Object>> dictSql = handlerService.findBySql("select code, name from sys_dict where pid in (select id from sys_dict where code = 'po_quotamethod')");
            if (CollectionUtils.isNotEmpty(dictSql)) {
                return PageResult.<Map<String, Object>>builder().data(dictSql).code(0).count((long) dictSql.size()).build();
            }
        } else if ("getPurchaseType".equals(type)) {
            String purchasecategory = MapUtils.getString(params, "purchasecategory");
            String itemtype = MapUtils.getString(params, "itemtype");
            String projecttype = MapUtils.getString(params, "projecttype");
            String purchaseway = MapUtils.getString(params, "purchaseway");
            String quotamethod = MapUtils.getString(params, "quotamethod");

            switch (purchasecategory) {
                case "物资":
                    if (StringUtils.isEmpty(itemtype) || StringUtils.isEmpty(projecttype) || StringUtils.isEmpty(purchaseway)) {
                        return null;
                    }
                    break;
                case "服务":
                    if (StringUtils.isEmpty(itemtype) || StringUtils.isEmpty(quotamethod)) {
                        return null;
                    }
                    break;
                case "生产外协":
                case "科研外协":
                    if (StringUtils.isEmpty(itemtype)) {
                        return null;
                    }
                    break;
                default:
                    break;
            }

            StringBuilder sb = new StringBuilder();
            switch (purchasecategory) {
                case "物资":
                    if ("政府采购".equals(projecttype) && "线下采购".equals(purchaseway)) {
                        sb.append("'公开招标','邀请招标','竞争性谈判','竞争性磋商','单一来源','询价','其他方式'");
                    } else if ("非政府采购".equals(projecttype)) {
                        switch (purchaseway) {
                            case "线下采购":
                                sb.append("'谈判采购','询比采购','直接采购','小额零星直接实施','小额零星比价实施'");
                                break;
                            case "电商采购":
                                sb.append("'电商直购','网上比选'");
                                break;
                            default:
                                break;
                        }

                    }
                    break;

                case "服务":
                    switch (itemtype) {
                        case "D2类":
                        case "D3类":
                        case "D4类":
                            switch (quotamethod) {
                                case "限额以上":
                                    sb.append("'公开招标','邀请招标','竞争性谈判','竞争性磋商','单一来源','询价','其他方式'");
                                    break;
                                case "限额以下":
                                    sb.append("'谈判','询比','直接采购'");
                                    break;
                                default:
                                    break;
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case "生产外协":
                    switch (itemtype) {
                        case "C1类":
                        case "C2类":
                        case "C3类":
                        case "C4类":
                        case "C5类":
                            sb.append("'谈判','框架协议','询比','直接外协','小额零星'");
                            break;
                        default:
                            break;
                    }
                    break;
                case "科研外协":
                    sb.append("'直接外协','谈判','询比'");
                    break;
                default:
                    break;
            }

            // 查询数据字典信息
            List<Map<String, Object>> dictSql = handlerService.findBySql("select code, name from sys_dict where " +
                    " pid in (select id from sys_dict where code = 'po_purchasetype')" +
                    " and code in (" + sb + ")");

            if (CollectionUtils.isNotEmpty(dictSql)) {
                return PageResult.<Map<String, Object>>builder().data(dictSql).code(0).count((long) dictSql.size()).build();
            }
        }
        return null;
    }

    @Override
    public String validateSave(String app, String objName, Map<String, Object> data) throws Exception {
        if ("gq_purchaseplan".equals(objName)) {
            Integer ppid = MapUtils.getInteger(data, "id");

            if (null == ppid) {
                return null;
            }

            String purchasecategory = MapUtils.getString(data, "purchasecategory");

            // 查询采购计划表信息
            List<Map<String, Object>> ppList = handlerService.findBySql("select purchasecategory from gq_purchaseplan t where t.purchasecategory is not null and t.id = " + ppid);

            if (CollectionUtils.isEmpty(ppList)) {
                return null;
            }

            Map<String, Object> ppMap = ppList.get(0);
            String oldpurchasecategory = MapUtils.getString(ppMap, "purchasecategory");

            if (!purchasecategory.equals(oldpurchasecategory)) {
                // 查询采购计划子表信息
                List<Map<String, Object>> pplList = handlerService.findBySql("select id from gq_ppline t where t.ppid = " + ppid);

                if (CollectionUtils.isNotEmpty(pplList)) {
                    return "已经维护了采购需求行, 如果需要修改则需要先删除采购需求行!";
                }
            }
        }

        return null;
    }

    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//        if ("gq_ppsummaryline".equals(objName)&&isUpdate) {
//
//            handlerService.updateBySql("delete from gq_ppsummaryline where id =  "+MapUtils.getInteger(data,"id"));
//        }
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        //汇总行统计
        System.out.println("objName ==="+objName+"=======isupdate==="+isUpdate);

        if ("gq_ppsummaryline".equals(objName)&&isUpdate==true) {
            //查询明细行数据就行统计

            List<Map<String,Object>> pplList = handlerService.findBySql("select * from gq_ppline where ppid = "+data.get("ppid") +" and ppslid = "+data.get("id"));
            if(CollectionUtils.isNotEmpty(pplList)){
                //先把汇总行数据进行还原，数量加减的字段
                //            handlerService.updateBySql("update gq_ppsummaryline set orderqty = orderqty + " + orderqty + "
                //            ,number=orderqty+" + orderqty + ", totalcost = totalcost + " + linecost + ", unitcost = ROUND(totalcost / orderqty,4 )" + whereSql);
                String sql = "update gq_ppsummaryline set orderqty =0,number=0,totalcost=0,unitcost=0,agetotalcost=0 where id = "+data.get("id");
                handlerService.updateBySql(sql);
                for (Map<String, Object> stringObjectMap : pplList) {
                    //重新统计明细行数据到汇总行
                    dealSummary(stringObjectMap);
                }
            }
        }

        if ("gq_ppline".equals(objName)&&isUpdate==false) {
            Integer ppid = MapUtils.getInteger(data, "ppid");
            Integer ppslid = MapUtils.getInteger(data, "ppslid");

            // 统计采购计划汇总信息  去掉第一次的限制
            //if (ppslid == null || ppslid == 0) {
            dealSummary(data);
            // }

            // 汇总计划明细表总金额并更新计划主表信息
            List<Map<String, Object>> pplList = handlerService.findBySql("select id, linecost from gq_ppline where ppid = " + ppid);

            if (CollectionUtils.isNotEmpty(pplList)) {
                // 组织插入数据
//                float prTotalcost = 0f;
                BigDecimal prTotalcost = new BigDecimal("0");
                for (Map<String, Object> pplMap : pplList) {
                    Integer pplid = (Integer) pplMap.get("id");
//                    float linecost = (float) pplMap.get("linecost");
                    String linecost = MapUtils.getString(pplMap, "linecost");
                    BigDecimal bigDecimal1 = new BigDecimal(linecost);
                    prTotalcost = prTotalcost.add(bigDecimal1);
//                    prTotalcost = prTotalcost + linecost;

                    handlerService.updateBySql("update gq_ppline set converttopo = '0' where converttopo is null and id = " + pplid);
                    handlerService.updateBySql("update gq_ppline set converttorfq = '0' where converttorfq is null and id = " + pplid);
                }

                // 修改采购计划信息
                handlerService.updateBySql("update gq_purchaseplan set totalcost = " + prTotalcost + " where id = " + ppid);
                // 修改采购计划是否存在子表数据
                handlerService.updateBySql("update gq_purchaseplan set haschild = 1 where haschild = 0 and id = " + ppid);
            }
        }
        if ("gq_purchaseplan".equals(objName)){
            String id = MapUtils.getString(data, "id");
            List<Map<String, Object>> bySql = handlerService.findBySql("select linecost from gq_ppline where ppid='" + id + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                BigDecimal bigDecimal1 = new BigDecimal("0");
                for (int i=0;i<bySql.size();i++){
                    Map<String, Object> map = bySql.get(i);
                    String linecost = MapUtils.getString(map, "linecost");
                    BigDecimal bigDecimal = new BigDecimal(linecost);
                    bigDecimal1=bigDecimal1.add(bigDecimal);
                }
                handlerService.updateBySql("update gq_purchaseplan set totalcost="+bigDecimal1+" where id='"+id+"'");
            }else {
                handlerService.updateBySql("update gq_purchaseplan set totalcost=0 where id='"+id+"'");
            }

        }

    }

    @SneakyThrows
    @Override
    public void beforDelete(String app, String objName, Long id, boolean isLogic) {
        if ("gq_ppline".equals(objName)) {
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_ppline t where t.id != " + id + " and t.ppid = (select ppid from gq_ppline where id = " + id + ")");

            if (CollectionUtils.isEmpty(list)) {
                // 修改采购申请是否存在子表数据
                handlerService.updateBySql("update gq_purchaseplan set haschild = 0 where haschild = 1 and id = (select ppid from gq_ppline where id = " + id + ")");
            }

            // 查询删除采购计划明细行信息
            List<Map<String, Object>> pplList = handlerService.findBySql("select ppid, ppslid, orderqty, linecost from gq_ppline t where t.id = " + id);
            Map<String, Object> pplMap = pplList.get(0);
            Integer ppid = MapUtils.getInteger(pplMap, "ppid");
            Integer ppslid = MapUtils.getInteger(pplMap, "ppslid");
            Float orderqty = MapUtils.getFloat(pplMap, "orderqty");
            Float linecost = MapUtils.getFloat(pplMap, "linecost");

            // 查询删除采购计划明细行对应采购计划汇总行信息
            List<Map<String, Object>> ppslList = handlerService.findBySql("select id, orderqty, totalcost from gq_ppsummaryline t where t.id = " + ppslid);
            if (CollectionUtils.isNotEmpty(ppslList)) {
                Map<String, Object> ppslMap = ppslList.get(0);
                Float ppslorderqty = MapUtils.getFloat(ppslMap, "orderqty");
                Float ppsltotalcost = MapUtils.getFloat(ppslMap, "totalcost");

                // 计算采购计划汇总行剩余采购数量和金额
                float ppslsurplusorderqty = ppslorderqty - orderqty;
                float ppslsurplustotalcost = ppsltotalcost - linecost;

                if (ppslsurplusorderqty > 0f) {
                    // 更新采购计划汇总行
                    handlerService.updateBySql("update gq_ppsummaryline set orderqty = " + ppslsurplusorderqty + ", totalcost = " + ppslsurplustotalcost + ", unitcost = totalcost/orderqty where ppid = " + ppid + " and id = " + ppslid);
                } else {
                    // 删除采购计划汇总行
                    handlerService.updateBySql("delete from gq_ppsummaryline where ppid = " + ppid + " and id = " + ppslid);
                }
            }
            //更新采购计划主表金额
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select totalcost from gq_purchaseplan where id='" + ppid + "'");
            if (CollectionUtils.isNotEmpty(bySql1)){
                List<Map<String, Object>> bySql = handlerService.findBySql("select linecost from gq_ppline where id='" + id + "'");
                if (CollectionUtils.isNotEmpty(bySql)){
                    Map<String, Object> map = bySql.get(0);
                    String linecost1 = MapUtils.getString(map, "linecost");
                    String totalcost = MapUtils.getString(bySql1.get(0), "totalcost");
                    BigDecimal bigDecimal = new BigDecimal(linecost1);
                    BigDecimal bigDecimal1 = new BigDecimal(totalcost);
                    bigDecimal1=bigDecimal1.subtract(bigDecimal);
                    handlerService.updateBySql("update gq_purchaseplan set totalcost="+bigDecimal1+" where id='"+ppid+"'");
                }
            }

            /*
             * 更新采购计划总金额
             */
            // 汇总计划明细表总金额并更新计划主表信息
//            pplList = handlerService.findBySql("select id, linecost from gq_ppline where ppid = " + ppid);
//
//            if (CollectionUtils.isNotEmpty(pplList)) {
//                // 组织插入数据
//                BigDecimal ppTotalcost = new BigDecimal("0");
//                for (Map<String, Object> map : pplList) {
//                    //修改下面错误
//                    String price = MapUtils.getString(map, "linecost");
////                    String price = (String)map.get("linecost");
//                    BigDecimal pplinecost = new BigDecimal(price);
//                    ppTotalcost = ppTotalcost.add(pplinecost);
//                }
//
//                // 修改采购计划信息
//                handlerService.updateBySql("update gq_purchaseplan set totalcost = " + ppTotalcost + " where id = " + ppid);
//            }
        }else{
            if("gq_ppsummaryline".equals(objName)){
                //根据汇总行id  查出对应的所有明细行数据
                List<Map<String, Object>> bySql = handlerService.findBySql("select id,ppid from gq_ppline where ppslid = " + id);
                if(CollectionUtils.isNotEmpty(bySql)){
                    StringJoiner stringJoiner = new StringJoiner(",");
                    for (Map<String, Object> map : bySql) {
                        String id1 = MapUtils.getString(map, "id");
                        stringJoiner.add(id1);
                    }
                    handlerService.findBySql("delete from gq_ppline where id in (" +stringJoiner.toString() + ")");
                    //更新采购计划总金额
                    String ppid = MapUtils.getString(bySql.get(0), "ppid");//采购计划id
//                    // 汇总计划明细表总金额并更新计划主表信息
//                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select id, linecost from gq_ppline where ppid = " + ppid);
//
//                    if (CollectionUtils.isNotEmpty(bySql1)) {
//                        BigDecimal ppTotalcost = new BigDecimal("0");
//                        for (Map<String, Object> map : bySql1) {
//                            String price = MapUtils.getString(map, "linecost");
//                            BigDecimal pplinecost = new BigDecimal(price);
//                            ppTotalcost = ppTotalcost.add(pplinecost);
//                        }
//
//                        // 修改采购计划信息
//                        handlerService.updateBySql("update gq_purchaseplan set totalcost = " + ppTotalcost + " where id = " + ppid);
//                    }
                    //更新采购计划主表金额
                    List<Map<String, Object>> bySql1 = handlerService.findBySql("select totalcost from gq_purchaseplan where id='" + ppid + "'");
                    if (CollectionUtils.isNotEmpty(bySql1)){
                        List<Map<String, Object>> bySql2 = handlerService.findBySql("select totalcost from gq_ppsummaryline where id='" + id + "'");
                        if (CollectionUtils.isNotEmpty(bySql2)){
                            Map<String, Object> map = bySql2.get(0);
                            String totalcost1 = MapUtils.getString(map, "totalcost");
                            String totalcost = MapUtils.getString(bySql1.get(0), "totalcost");
                            BigDecimal bigDecimal = new BigDecimal(totalcost1);
                            BigDecimal bigDecimal1 = new BigDecimal(totalcost);
                            bigDecimal1=bigDecimal1.subtract(bigDecimal);
                            handlerService.updateBySql("update gq_purchaseplan set totalcost="+bigDecimal1+" where id='"+ppid+"'");
                        }
                    }
                }
            }
        }
    }

    /**
     * 处理采购计划汇总行
     *
     * @return
     */
    private void dealSummary(Map<String, Object> data) throws Exception {
        Integer prlid = MapUtils.getInteger(data, "prlid");
        Integer ppid = MapUtils.getInteger(data, "ppid");
        String ppNum = MapUtils.getString(data, "ppnum");
        String itemNum = MapUtils.getString(data, "itemnum");
        List<Map<String, Object>> sql = handlerService.findBySql("select id from gq_item where itemnum='" + itemNum + "'");
        String itemid = MapUtils.getString(sql.get(0), "id");
//        float linecost = MapUtils.getFloat(data, "linecost");
                String linecost1 = MapUtils.getString(data, "linecost");
        BigDecimal linecost = new BigDecimal(linecost1);
        float orderqty = MapUtils.getFloat(data, "orderqty");
        String unitcost1 = MapUtils.getString(data, "unitcost");
        String subjectno = MapUtils.getString(data, "subjectno");//课题号
        String itemdesc = MapUtils.getString(data, "itemdesc");//物料名称
        String model = MapUtils.getString(data, "model");//型号
        String spemodel = MapUtils.getString(data, "spemodel");//品牌
        String orderunit = MapUtils.getString(data, "orderunit");//计量单位
        String packform = MapUtils.getString(data, "packform");//封装形式
        String maintechtors = MapUtils.getString(data, "maintechtors");//主要技术指标
        String specifications = MapUtils.getString(data, "specifications");//规格
        String qualitygrade = MapUtils.getString(data, "qualitygrade");//质量/机械性能/精度
        BigDecimal unitcost = new BigDecimal(unitcost1);
        BigDecimal bigDecimal3 = new BigDecimal(orderqty);
        BigDecimal bigDecimal4 = new BigDecimal("0");
        bigDecimal4=bigDecimal3.multiply(unitcost);
//        float unitcost = MapUtils.getFloat(data, "unitcost");
        boolean flag = true;

        // 查询采购计划汇总配置主表信息
        List<Map<String, Object>> ppcList = handlerService.findBySql("select id, appid, appnum, tablename from gq_ppconfig where ppcnum = 'ppc10'");
        if (CollectionUtils.isEmpty(ppcList)) {
            flag = false;
        }
        Map<String, Object> ppcMap = ppcList.get(0);
        Integer ppcId = MapUtils.getInteger(ppcMap, "id");

        // 查询采购计划汇总配置子表信息
        List<Map<String, Object>> ppclList = handlerService.findBySql("select fieldname, islinked from gq_ppconfigline where ppcid = " + ppcId);
        if (CollectionUtils.isEmpty(ppclList)) {
            flag = false;
        }

        StringBuilder whereSql = new StringBuilder();
        whereSql.append(" ppid = ").append(ppid).append(" and itemnum = '").append(itemNum).append("'");
        if (flag) {
            whereSql = new StringBuilder();
            whereSql.append(" where 1 = 1 ");
            // 组织查询sql
            for (Map<String, Object> ppclMap : ppclList) {
                String fieldName = MapUtils.getString(ppclMap, "fieldname");

                for (Map.Entry<String, Object> entry : data.entrySet()) {
                    if (fieldName.equals(entry.getKey())) {
                        whereSql.append(" and ");
                        whereSql.append(fieldName);
                        whereSql.append(" = ");
                        whereSql.append("'");
                        whereSql.append(entry.getValue());
                        whereSql.append("'");
                    }
                }
            }
            whereSql.append(" and ppid = ");
            whereSql.append(ppid);
        }

        // 是否存在采购计划汇总信息
        List<Map<String, Object>> tempList = handlerService.findBySql("select id,totalcost,orderqty from gq_ppsummaryline " + whereSql);
        Integer ppslid = 0;
        if (CollectionUtils.isEmpty(tempList)) {
            Map<String, Object> map = new HashMap<>();
            //加个顺序
            // LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            map.put("ppid", ppid);
            map.put("ppnum", ppNum);

            if (flag) {
                // 组织查询sql
                for (Map<String, Object> ppclMap : ppclList) {
                    String fieldName = MapUtils.getString(ppclMap, "fieldname");

                    for (Map.Entry<String, Object> entry : data.entrySet()) {
                        if (fieldName.equals(entry.getKey())) {
                            map.put(fieldName, entry.getValue());
                        }
                    }
                }
            } else {
                map.put("itemnum", data.get("itemnum"));
                map.put("itemdesc", data.get("itemdesc"));
                map.put("orderunit", data.get("orderunit"));
                map.put("model", data.get("model"));
                map.put("spemodel", data.get("spemodel"));
                map.put("qualitygrade", data.get("qualitygrade"));//质量/机械性能/精度
                map.put("packform", data.get("packform"));
                map.put("manufacturer", data.get("manufacturer"));
                map.put("maintechtors", data.get("maintechtors"));//主要技术指标
                map.put("specifications", data.get("specifications"));//规格
                map.put("isinspection", data.get("isinspection"));
                map.put("purchasemethod", data.get("purchasemethod"));
            }
            map.put("itemid",itemid);
            map.put("orderqty", orderqty);
            map.put("number", orderqty);
            map.put("unitcost", unitcost);
            map.put("totalcost", linecost);
            BigDecimal bigDecimal = new BigDecimal("0");
            bigDecimal=unitcost.multiply(bigDecimal3);
            map.put("agetotalcost",bigDecimal);
            map.put("converttopo", 0);
            map.put("converttorfq", 0);
            map.put("converttorfq1", 0);
            map.put("ordernot",0);
            map.put("subjectno", subjectno);
            map.put("maintechtors", maintechtors);//主要技术指标
            map.put("qualitygrade", qualitygrade);//质量/机械性能/精度
            map.put("specifications", specifications);//规格
            map.put("itemdesc", itemdesc);
            map.put("model", model);
            map.put("spemodel", spemodel);
            map.put("orderunit", orderunit);
            map.put("packform", packform);
            map.put("manufacturer", data.get("manufacturer"));//生产厂家
            map.put("isinspection", data.get("isinspection"));//是否送检

            BigInteger tmpppslid = (BigInteger) handlerService.insert("gq_ppsummaryline", map);
            ppslid = tmpppslid.intValue();
            // 更新采购计划明细行状态
            handlerService.updateBySql("update gq_ppline set ppslid = " + ppslid + " where prlid = " + prlid);
        } else {
            Map<String, Object> ppslMap = tempList.get(0);
            ppslid = MapUtils.getInteger(ppslMap, "id");

            // 更新采购计划汇总行信息
            handlerService.updateBySql("update gq_ppsummaryline set orderqty = orderqty + " + orderqty + ",number=number+" + orderqty + ", totalcost = totalcost + " + linecost + ",agetotalcost= agetotalcost+"+bigDecimal4+" " + whereSql);
            List<Map<String, Object>> bySql = handlerService.findBySql("select id,totalcost,orderqty,agetotalcost from gq_ppsummaryline " + whereSql);
            if (CollectionUtils.isNotEmpty(bySql)){
                Map<String, Object> map = bySql.get(0);
                String totalcost = MapUtils.getString(map, "totalcost");
                String agetotalcost = MapUtils.getString(map, "agetotalcost");
                String orderqty1 = MapUtils.getString(map, "orderqty");
                BigDecimal bigDecimal = new BigDecimal(totalcost);
                BigDecimal bigDecimal1 = new BigDecimal(orderqty1);
                BigDecimal bigDecimal2 = new BigDecimal("0");
                BigDecimal bigDecimal5 = new BigDecimal(agetotalcost);
                bigDecimal2=bigDecimal5.divide(bigDecimal1,4,BigDecimal.ROUND_HALF_UP);
                handlerService.updateBySql("update gq_ppsummaryline set unitcost="+bigDecimal2+"" + whereSql);
                // 更新采购计划明细行状态
                 handlerService.updateBySql("update gq_ppline set ppslid = " + ppslid + " where prlid = " + prlid);
            }
        }

        // 更新采购计划明细行状态
       // handlerService.updateBySql("update gq_ppline set ppslid = " + ppslid + " where prlid = " + prlid);
    }



//    @Override
//    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//        if ("purchaseplanApp".equals(app)){
//            if (isUpdate==false)
//            if ("gq_ppline".equals(objName)){
//                String id = MapUtils.getString(data, "id");
//                String ppid = MapUtils.getString(data, "ppid");
//                String prid = MapUtils.getString(data, "prid");
//                List<Map<String, Object>> bySql = handlerService.findBySql("select prnum from gq_pr where id='" + prid + "'");
//                if(CollectionUtils.isNotEmpty(bySql)){
//                    String prnum = MapUtils.getString(bySql.get(0), "prnum");
//                    handlerService.updateBySql("update gq_ppline set prnum='"+prnum+"' where id='"+id+"'");
//                }
//            }
//        }
//        super.beforSave(app, objName, data, isUpdate);
//    }

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if ("purchaseplanApp".equals(app)){
            if (flowNode.getId().equals("fqr")){
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_ppline where ppid='" + id + "'");
                if (CollectionUtils.isNotEmpty(bySql)){
                    for (int i=0;i<bySql.size();i++){
                        Map<String, Object> map = bySql.get(i);
                        String prlid = MapUtils.getString(map, "prlid");//采购申请行id
                        String orderqty = MapUtils.getString(map, "orderqty");//采购数量
                        String prid = MapUtils.getString(map, "prid");//采购申请id
                        String id1 = MapUtils.getString(map, "id");
                        List<Map<String, Object>> bySql1 = handlerService.findBySql("select t.orderqty from gq_ppline t left join gq_purchaseplan a on t.ppid=a.id where t.id!='" + id1 + "' and prlid='"+prlid+"' and a.status !='新建' and a.status !='已作废'");
                        if (CollectionUtils.isNotEmpty(bySql1)){
                            int y = i + 1;
                            return "采购计划物料第" + y + "条数据中物料被人占用，请重新选择物料！";
                        }
                        List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_prchange where prid='" + prid + "' and status!='新建' and status!='已作废' and status!='已批准'");
                        if(CollectionUtils.isNotEmpty(bySql2)){
                            return "采购申请变更已提交，请重新选择";
                        }
                    }
                }else {
                    return "请添加采购申请行信息！";
                }
            }
        }
        return super.beforeExcuteFlow(app, id, flowNode, op);
    }
}
